package org.grow.jpago.controller;

import com.querydsl.jpa.impl.JPAQueryFactory;
import org.grow.jpago.dao.PersonDao;
import org.grow.jpago.entity.Person;
import org.grow.jpago.entity.PersonPagedCondition;
import org.grow.jpago.entity.QPerson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author: xwg
 * @CreateDate: 21-7-14
 */

@RestController
public class PersonController {
    @Autowired
    private PersonDao personDao;
    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    @PostMapping("/person")
    public Person insert(@RequestBody Person person){
        person.setPersonId(0);

//        insert 新增 和updateById的合体
        Person save = personDao.save(person);
        return save;
    }
    QPerson p = QPerson.person;
    //select * from Person p limit pageStart, pageSize;
    @PostMapping("/queryPersons")
    public List<Person> query(@RequestBody PersonPagedCondition personPagedCondition){

        Integer pageNum = personPagedCondition.getPageNum();
        Integer pageSize = personPagedCondition.getPageSize();
        Integer pageStart = (pageNum-1)*pageSize;
        List<Person> fetch = jpaQueryFactory.selectFrom(p)
                .orderBy(p.age.desc())
                .offset(pageStart)
                .limit(pageSize)
                .fetch();
        fetch.forEach(x->{
            System.out.println(x);
        });
        return fetch;
    }

}
